<template>
  <div class="vote-container">
	<el-row type="flex" justify="center" class="page-header" style="margin-bottom: 30px;">
	        <el-col :span="24" class="text-center">
	            <div class="title-wrapper">
	            <i class="el-icon-search el-icon--large"></i>
	            <h1 class="main-title">投票信息管理系统</h1>
	            <p class="sub-title">每一张选票都是信任的传递，每一次统计都是责任的坚守，用心维护投票的公正，让每份意愿都被尊重</p>
	            </div>
	        </el-col>
	    </el-row>
    <!-- 详情对话框 -->
   <el-dialog
     v-model="dialogVisible"
     title="投票详情"
     width="70%"
     destroy-on-close
   >
     <el-descriptions title="投票信息" direction="vertical" :column="4" border>
       <el-descriptions-item label="投票ID" :span="2">{{ currentVote.id }}</el-descriptions-item>
       <el-descriptions-item label="标题" :span="2">{{ currentVote.title }}</el-descriptions-item>
       <el-descriptions-item label="最大可选数" :span="2">{{ currentVote.maxOptions }}</el-descriptions-item>
       <el-descriptions-item label="状态" :span="2">
         <el-tag :type="getStatusTagType(currentVote.status)">{{ currentVote.status }}</el-tag>
       </el-descriptions-item>
       <el-descriptions-item label="开始时间" :span="2">{{ formatDateTime(currentVote.startTime) }}</el-descriptions-item>
       <el-descriptions-item label="结束时间" :span="2">{{ formatDateTime(currentVote.endTime) }}</el-descriptions-item>
       <el-descriptions-item label="描述" :span="4">{{ currentVote.description || '无' }}</el-descriptions-item>
     </el-descriptions>
     
     <el-divider content-position="left">投票选项</el-divider>
     <el-table :data="currentVote.options" border style="width: 100%; margin-bottom: 20px;">
       <el-table-column prop="id" label="选项ID" width="80" align="center"></el-table-column>
       <el-table-column prop="text" label="选项内容" align="center"></el-table-column>
       <el-table-column prop="voteCount" label="得票数" width="100" align="center"></el-table-column>
     </el-table>
     
     <el-divider content-position="left">投票记录</el-divider>
     <el-table :data="currentVote.records" border style="width: 100%;">
       <el-table-column prop="id" label="记录ID" width="80" align="center"></el-table-column>
       <el-table-column prop="userName" label="用户名" width="120" align="center"></el-table-column>
       <el-table-column prop="optionId" label="选项ID" width="100" align="center"></el-table-column>
       <el-table-column prop="votedAt" label="投票时间" width="180" align="center">
         <template #default="scope">{{ formatDateTime(scope.row.votedAt) }}</template>
       </el-table-column>
     </el-table>
   </el-dialog>


    <!-- 编辑对话框 -->
    <el-dialog
      v-model="editDialogVisible"
      title="编辑投票信息"
      width="60%"
      destroy-on-close
    >
      <el-form 
        :model="editForm" 
        :rules="rules" 
        ref="editFormRef" 
        label-width="120px" 
        class="demo-ruleForm"
      >
        <el-form-item label="投票ID" prop="id" disabled>
          <el-input v-model="editForm.id"></el-input>
        </el-form-item>
        <el-form-item label="标题" prop="title">
          <el-input v-model="editForm.title"></el-input>
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input v-model="editForm.description" type="textarea" rows="3"></el-input>
        </el-form-item>
        <el-form-item label="最大可选数" prop="maxOptions">
          <el-input v-model.number="editForm.maxOptions" type="number" min="1"></el-input>
        </el-form-item>
        <el-form-item label="开始时间" prop="startTime">
          <el-date-picker
            v-model="editForm.startTime"
            type="datetime"
            format="YYYY-MM-DD HH:mm:ss"
            value-format="YYYY-MM-DD HH:mm:ss"
            placeholder="选择开始时间"
          ></el-date-picker>
        </el-form-item>
        <el-form-item label="结束时间" prop="endTime">
          <el-date-picker
            v-model="editForm.endTime"
            type="datetime"
            format="YYYY-MM-DD HH:mm:ss"
            value-format="YYYY-MM-DD HH:mm:ss"
            placeholder="选择结束时间"
          ></el-date-picker>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitEditForm">确定</el-button>
          <el-button @click="editDialogVisible = false">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>


    <!-- 新增对话框 -->
    <el-dialog
      v-model="addDialogVisible"
      title="新增投票"
      width="60%"
      destroy-on-close
    >
      <el-form 
        :model="addForm" 
        :rules="rules" 
        ref="addFormRef" 
        label-width="120px"
      >
        <el-form-item label="标题" prop="title">
          <el-input v-model="addForm.title"></el-input>
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input v-model="addForm.description" type="textarea" rows="3"></el-input>
        </el-form-item>
        <el-form-item label="最大可选数" prop="maxOptions">
          <el-input v-model.number="addForm.maxOptions" type="number" min="1" placeholder="至少选择1项"></el-input>
        </el-form-item>
        <el-form-item label="开始时间" prop="startTime">
          <el-date-picker
            v-model="addForm.startTime"
            type="datetime"
            format="YYYY-MM-DD HH:mm:ss"
            value-format="YYYY-MM-DD HH:mm:ss"
            placeholder="选择开始时间"
          ></el-date-picker>
        </el-form-item>
        <el-form-item label="结束时间" prop="endTime">
          <el-date-picker
            v-model="addForm.endTime"
            type="datetime"
            format="YYYY-MM-DD HH:mm:ss"
            value-format="YYYY-MM-DD HH:mm:ss"
            placeholder="选择结束时间"
          ></el-date-picker>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitAddForm">提交</el-button>
          <el-button @click="addDialogVisible = false">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>


    <!-- 添加选项对话框 -->
    <el-dialog
      v-model="addOptionDialogVisible"
      title="添加投票选项"
      width="50%"
      destroy-on-close
    >
      <el-form 
        :model="optionForm" 
        :rules="optionRules" 
        ref="optionFormRef" 
        label-width="120px"
      >
        <el-form-item label="投票ID" prop="voteId" disabled>
          <el-input v-model="optionForm.voteId"></el-input>
        </el-form-item>
        <el-form-item label="选项内容" prop="optionText">
          <el-input v-model="optionForm.optionText" placeholder="请输入选项内容"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitAddOption">确定</el-button>
          <el-button @click="addOptionDialogVisible = false">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>


    <!-- 数据操作区 -->
    <el-row>
      <el-row :gutter="10" style="width: 100%; margin-bottom: 20px; align-items: center;">
        <el-col :span="6">
          <el-input 
            placeholder="输入投票ID进行查询" 
            v-model="searchId" 
            style="width: 100%;"
            @keyup.enter="handleSearch"
          ></el-input>
        </el-col>
        <el-col :span="4">
          <el-select 
            v-model="searchStatus" 
            placeholder="按状态筛选" 
            style="width: 100%;"
          >
            <el-option label="全部状态" value=""></el-option>
            <!-- <el-option label="DRAFT" value="DRAFT"></el-option> -->
            <el-option label="PENDING" value="PENDING"></el-option>
            <el-option label="ACTIVE" value="ACTIVE"></el-option>
            <el-option label="CLOSED" value="CLOSED"></el-option>
          </el-select>
        </el-col>
        <el-col :span="2">
          <el-button 
            type="primary" 
            @click="handleSearch" 
            style="width: 100%;"
          >
            <i class="el-icon-search"></i> 搜索
          </el-button>
        </el-col>
        <el-col :span="2">
          <el-button 
            type="success" 
            @click="resetSearch" 
            style="width: 100%;"
          >
            <i class="el-icon-refresh"></i> 重置
          </el-button>
        </el-col>
        <el-col :span="2">
          <el-button 
            type="primary" 
            @click="openAddDialog" 
            style="width: 100%;"
          >
            <i class="el-icon-plus"></i> 新增
          </el-button>
        </el-col>
      </el-row>
      
      <!-- 表格部分 -->
      <el-table 
        :data="filteredData.slice((currentPage-1)*pageSize, currentPage*pageSize)" 
        border 
        style="width: 100%;"
        height="450"
        @sort-change="handleSortChange"
      >
        <el-table-column 
          prop="id" 
          label="投票ID" 
          width="100" 
          align="center" 
          sortable="custom"
        ></el-table-column>
        <el-table-column prop="title" label="标题" align="center"></el-table-column>
        <el-table-column prop="maxOptions" label="最大可选数" width="120" align="center"></el-table-column>
        <el-table-column 
          prop="status" 
          label="状态" 
          width="120" 
          align="center"
        >
          <template #default="scope">
            <el-tag :type="getStatusTagType(scope.row.status)">
              {{ scope.row.status }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column 
          prop="startTime" 
          label="开始时间" 
          width="180" 
          align="center" 
          sortable="custom"
        >
          <template #default="scope">{{ formatDateTime(scope.row.startTime) }}</template>
        </el-table-column>
        <el-table-column 
          prop="endTime" 
          label="结束时间" 
          width="180" 
          align="center" 
          sortable="custom"
        >
          <template #default="scope">{{ formatDateTime(scope.row.endTime) }}</template>
        </el-table-column>
        <el-table-column label="操作" width="300" fixed="right">
          <template #default="scope">
            <div class="operation-buttons">
              <el-button type="primary" size="mini" @click="openDetailDialog(scope.row)" 
                :disabled="!scope.row">
                <i class="el-icon-view"></i> 查看
              </el-button>
              <el-button type="warning" size="mini" @click="openEditDialog(scope.row)" 
                :disabled="!canEdit(scope.row.status)">
                <i class="el-icon-edit"></i> 编辑
              </el-button>
              <el-button type="success" size="mini" @click="activateVote(scope.row.id)"
                :disabled="scope.row.status !== 'PENDING'">
                <i class="el-icon-check"></i> 激活
              </el-button>
              <el-button type="info" size="mini" @click="openAddOptionDialog(scope.row.id)"
                :disabled="!canEdit(scope.row.status)">
                <i class="el-icon-plus"></i> 选项
              </el-button>
              <el-button type="danger" size="mini" @click="deleteVote(scope.row.id)"
                :disabled="!scope.row.id">
                <i class="el-icon-delete"></i> 删除
              </el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页 -->
      <el-row type="flex" justify="center" style="margin-top: 20px;">
        <el-pagination 
          @size-change="handleSizeChange" 
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="[5,10,20,50]" 
          :page-size="pageSize" 
          :total="filteredData.length"
          layout="total, sizes, prev, pager, next, jumper"
        ></el-pagination>
      </el-row>
    </el-row>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { post } from '../../utils/axios.js'
import { ElMessage, ElMessageBox, ElLoading } from 'element-plus'


// 对话框状态
const dialogVisible = ref(false)
const editDialogVisible = ref(false)
const addDialogVisible = ref(false)
const addOptionDialogVisible = ref(false)

// 搜索条件
const searchId = ref('')
const searchStatus = ref('')

// 分页相关
const currentPage = ref(1)
const pageSize = ref(10)

// 排序相关
const sortProp = ref('')
const sortOrder = ref('')

// 数据存储
const voteList = ref([])
const filteredData = ref([])

// 表单引用
const editFormRef = ref(null)
const addFormRef = ref(null)
const optionFormRef = ref(null)

// 当前选中的投票信息
const currentVote = reactive({
  id: '',
  title: '',
  description: '',
  maxOptions: 1,
  startTime: '',
  endTime: '',
  status: '',
  options: [],
  records: []
})

// 编辑表单数据
const editForm = reactive({
  id: '',
  title: '',
  description: '',
  maxOptions: 1,
  startTime: '',
  endTime: ''
})

// 新增表单数据
const addForm = reactive({
  title: '',
  description: '',
  maxOptions: 1,
  startTime: '',
  endTime: ''
})

// 选项表单数据
const optionForm = reactive({
  voteId: '',
  optionText: ''
})

// 表单验证规则
const rules = reactive({
  title: [
    { required: true, message: '请输入投票标题', trigger: 'blur' },
    { min: 1, max: 100, message: '标题长度在 1 到 100 个字符', trigger: 'blur' }
  ],
  maxOptions: [
    { required: true, message: '请输入最大可选数', trigger: 'blur' },
    { type: 'number', message: '必须是数字', trigger: 'blur' },
    { validator: (rule, value, callback) => {
      if (value < 1) {
        callback(new Error('最大可选数必须大于0'))
      } else {
        callback()
      }
    }, trigger: 'blur' }
  ],
  startTime: [
    { required: true, message: '请选择开始时间', trigger: 'change' }
  ],
  endTime: [
    { required: true, message: '请选择结束时间', trigger: 'change' },
    { validator: (rule, value, callback) => {
      if (value && editForm.startTime && new Date(value) <= new Date(editForm.startTime)) {
        callback(new Error('结束时间必须晚于开始时间'))
      } else if (value && addForm.startTime && new Date(value) <= new Date(addForm.startTime)) {
        callback(new Error('结束时间必须晚于开始时间'))
      } else {
        callback()
      }
    }, trigger: 'change' }
  ]
})

// 选项表单验证规则
const optionRules = reactive({
  optionText: [
    { required: true, message: '请输入选项内容', trigger: 'blur' },
    { min: 1, max: 200, message: '选项内容长度在 1 到 200 个字符', trigger: 'blur' }
  ]
})

// 根据状态获取标签类型
const getStatusTagType = (status) => {
  switch(status) {
    case 'ACTIVE': return 'success'
    case 'PENDING': return 'warning'
    case 'DRAFT': return 'info'
    case 'CLOSED': return 'danger'
    default: return ''
  }
}

// 判断是否可以编辑
const canEdit = (status) => {
  return status === 'DRAFT' || status === 'PENDING'
}

// 格式化日期时间
const formatDateTime = (dateTime) => {
  if (!dateTime) return '无'
  return new Date(dateTime).toLocaleString()
}

// 处理排序变化
function handleSortChange({ prop, order }) {
  sortProp.value = prop;
  sortOrder.value = order;
  if (prop && order) {
    filteredData.value = [...filteredData.value].sort((a, b) => {
      let valA = a[prop];
      let valB = b[prop];
      // 处理日期类型排序
      if (prop === 'startTime' || prop === 'endTime') {
        valA = new Date(valA);
        valB = new Date(valB);
      }
      // 升序/降序处理
      if (order === 'ascending') {
        return valA > valB ? 1 : -1;
      } else {
        return valA < valB ? 1 : -1;
      }
    });
  }
}

// 打开详情对话框
function openDetailDialog(row) {
  dialogVisible.value = true
  const loading = ElLoading.service({ text: '加载详情中...' })
  
  post('/sc/vote/detail', { voteId: row.id }, (res) => {
    loading.close()
    if (res.status === 1 && res.data) {
      Object.assign(currentVote, res.data.vote);
      currentVote.options = res.data.options || [];
      currentVote.records = res.data.records || [];
    } else {
      ElMessage.error(res.msg || '获取详情失败')
    }
  })
}

// 打开编辑对话框
function openEditDialog(vote) {
  editDialogVisible.value = true
  Object.assign(editForm, {
    id: vote.id,
    title: vote.title,
    description: vote.description,
    maxOptions: vote.maxOptions,
    startTime: vote.startTime,
    endTime: vote.endTime
  })
}

// 打开新增对话框
function openAddDialog() {
  addDialogVisible.value = true
  if (addFormRef.value) {
    addFormRef.value.resetFields()
  }
  // 设置默认值
  addForm.maxOptions = 1
  const now = new Date()
  addForm.startTime = formatDate(now)
  // 默认结束时间为1天后
  const tomorrow = new Date(now)
  tomorrow.setDate(tomorrow.getDate() + 1)
  addForm.endTime = formatDate(tomorrow)
}

// 打开添加选项对话框
function openAddOptionDialog(voteId) {
  addOptionDialogVisible.value = true
  if (optionFormRef.value) {
    optionFormRef.value.resetFields()
  }
  optionForm.voteId = voteId
  optionForm.optionText = ''
}

// 格式化日期为字符串
function formatDate(date) {
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  const hours = String(date.getHours()).padStart(2, '0')
  const minutes = String(date.getMinutes()).padStart(2, '0')
  const seconds = String(date.getSeconds()).padStart(2, '0')
  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
}

// 提交编辑表单
function submitEditForm() {
  editFormRef.value.validate((valid) => {
    if (!valid) return;
    
    const updateData = {
      voteId: editForm.id,
      title: editForm.title,
      description: editForm.description,
      maxOptions: editForm.maxOptions,
      startTime: editForm.startTime,
      endTime: editForm.endTime
    };
    
    const loading = ElLoading.service({ text: '更新中...' })
    post('/sc/vote/update', updateData, (res) => {
      loading.close()
      if (res.status === 1 || res.includes('成功')) {
        ElMessage.success('更新成功！')
        editDialogVisible.value = false
        fetchVoteList()
      } else {
        ElMessage.error(res.msg || '更新失败')
      }
    })
  })
}

// 提交新增表单
function submitAddForm() {
  addFormRef.value.validate((valid) => {
    if (!valid) return;
    
    const loading = ElLoading.service({ text: '添加中...' })
    post('/sc/vote/create', addForm, (res) => {
      loading.close()
      if (res.status === 1 || res.includes('成功')) {
        ElMessage.success('添加成功！')
        addDialogVisible.value = false
        fetchVoteList()
      } else {
        ElMessage.error(res.msg || '添加失败')
      }
    })
  })
}

// 提交添加选项
function submitAddOption() {
  optionFormRef.value.validate((valid) => {
    if (!valid) return;
    
    const loading = ElLoading.service({ text: '添加选项中...' })
    post('/sc/vote/addOption', optionForm, (res) => {
      loading.close()
      if (res.status === 1 || res.includes('成功')) {
        ElMessage.success('选项添加成功！')
        addOptionDialogVisible.value = false
        fetchVoteList()
      } else {
        ElMessage.error(res.msg || '添加失败')
      }
    })
  })
}

// 激活投票
function activateVote(voteId) {
  ElMessageBox.confirm('确定要激活该投票吗？', '确认', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'info'
  }).then(() => {
    const loading = ElLoading.service({ text: '激活中...' })
    post('/sc/vote/activate', { voteId }, (res) => {
      loading.close()
      if (res.status === 1 || res.includes('成功')) {
        ElMessage.success('激活成功！')
        fetchVoteList()
      } else {
        ElMessage.error(res.msg || '激活失败')
      }
    })
  }).catch(() => {})
}

// 删除投票
function deleteVote(voteId) {
  ElMessageBox.confirm(`确定删除ID为 ${voteId} 的投票吗？`, '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    const loading = ElLoading.service({ text: '删除中...' })
    post('/sc/vote/delete', { voteId }, (res) => {
      loading.close()
      if (res.status === 1 || res.includes('成功')) {
        ElMessage.success('删除成功！')
        fetchVoteList()
      } else {
        ElMessage.error(res.msg || '删除失败')
      }
    })
  }).catch(() => {})
}

// 搜索处理
function handleSearch() {
  const loading = ElLoading.service({ text: '搜索中...' })
  
  filteredData.value = voteList.value.filter(item => {
    const matchesId = !searchId.value || (item.id && item.id.toString().includes(searchId.value))
    const matchesStatus = !searchStatus.value || (item.status === searchStatus.value)
    return matchesId && matchesStatus
  })
  
  loading.close()
  showSearchResultMessage()
  currentPage.value = 1 // 重置到第一页
  
  // 应用当前排序
  if (sortProp.value && sortOrder.value) {
    handleSortChange({ prop: sortProp.value, order: sortOrder.value });
  }
}

// 显示搜索结果消息
function showSearchResultMessage() {
  if (filteredData.value.length > 0) {
    ElMessage.success(`找到 ${filteredData.value.length} 条记录`)
  } else {
    ElMessage.warning('未找到匹配记录')
  }
}

// 重置搜索
function resetSearch() {
  searchId.value = ''
  searchStatus.value = ''
  filteredData.value = [...voteList.value]
  currentPage.value = 1
  // 重置排序
  sortProp.value = ''
  sortOrder.value = ''
}

// 分页大小变化
function handleSizeChange(val) {
  pageSize.value = val
  currentPage.value = 1
}

// 当前页变化
function handleCurrentChange(val) {
  currentPage.value = val
}

// 获取所有投票信息
function fetchVoteList() {
  const loading = ElLoading.service({ text: '加载中...' })
  post('/sc/vote/getAll', {}, (res) => {
    loading.close()
    if (res.status === 1 && res.data) {
      voteList.value = res.data
      filteredData.value = [...res.data]
      // 应用排序
      if (sortProp.value && sortOrder.value) {
        handleSortChange({ prop: sortProp.value, order: sortOrder.value });
      }
    } else {
      ElMessage.error(res.msg || '获取数据失败')
      voteList.value = []
      filteredData.value = []
    }
  })
}

// 页面加载时获取数据
onMounted(() => {
  fetchVoteList()
})
</script>

<style scoped>
.vote-container {
  width: auto;
  padding: 20px;
}

/* 标题样式 */
.page-header {
  padding: 10px 0;
  border-bottom: 1px solid #e5e7eb;
}

.title-wrapper {
  display: inline-flex;
  flex-direction: column;
  align-items: flex-start;
  gap: 8px;
}

.main-title {
  font-size: 28px;
  font-weight: 600;
  color: #1f2937;
  margin: 0;
  display: flex;
  align-items: center;
  gap: 12px;
}

.sub-title {
  font-size: 16px;
  color: #6b7280;
  margin: 0;
}

.el-icon--large {
  font-size: 28px;
  color: #409eff;
}

.operation-buttons {
  display: flex;
  gap: 4px;
}

.operation-buttons .el-button--mini {
  padding: 1px 6px;
  font-size: 12px;
  height: 24px;
  min-width: auto;
}

.el-table {
  margin-top: 20px;
}

.el-pagination {
  margin-top: 20px;
}

.el-form-item .el-button,
.el-col .el-button {
  margin-right: 5px;
}

.el-form {
  padding: 10px;
}

.el-descriptions {
  margin-bottom: 20px;
}
</style>